package cn.renkai721.ws;
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import cn.renkai721.filter.HTMLFilter;

@ServerEndpoint(value = "/websocket/chat/{clientId}")
public class WebSocket {
	// 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
	private static int onlineCount = 0;
	private static final String GUEST_PREFIX = "Guest";
	private static final AtomicInteger connectionIds = new AtomicInteger(0);
	// concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
	private static final Set<WebSocket> connections = new CopyOnWriteArraySet<WebSocket>();

	private final String nickname;
	// 与某个客户端的连接会话，需要通过它来给客户端发送数据
	private Session session;

	public WebSocket() {
		nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
		System.out.println("每次浏览器的websocket连上服务器端，就会new 出本类的实例： " + nickname);
	}

	/**
	 * 连接建立成功调用的方法
	 * 
	 * @param session
	 *            可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
	 */
	@OnOpen
	public void onOpen(@PathParam("clientId") String clientId, Session session) {
		System.out.println("OnOpen! onopen方法会在每次连接上时触发: " + clientId);
		this.session = session;
		// 加入set中
		connections.add(this);
		// 在线数加1
		addOnlineCount();
		String message = String.format("* %s %s", nickname, "has joined.");
		broadcast(message);
		System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose(@PathParam("clientId") String clientId) {
		System.out.println("OnClose! " + clientId);
		// 从set中删除
		connections.remove(this);
		subOnlineCount(); // 在线数减1
		String message = String
				.format("* %s %s", nickname, "has disconnected.");
		broadcast(message);
		System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
	}

	/**
	 * 收到客户端消息后调用的方法
	 * 
	 * @param message
	 *            客户端发送过来的消息
	 * @param session
	 *            可选的参数
	 */
	@OnMessage
	public void onMessage(@PathParam("clientId") String clientId, String message) {
		System.out.println("来自客户端的消息:" + message);
		// Never trust the client
		System.out.println("OnMessage: " + clientId + ": " + message);
		String filteredMessage = String.format("%s: %s", nickname,
				HTMLFilter.filter(message.toString()));
		// 群发消息
		broadcast(filteredMessage);
	}

	private static void broadcast(String message) {
		for (WebSocket client : connections) {
			try {
				synchronized (client) {
					client.sendMessage(message);
				}
			} catch (IOException e) {
				System.out
						.println("Chat broadcast Error: Failed to send message to client");
				e.printStackTrace();
				connections.remove(client);
				try {
					client.session.close();
				} catch (IOException e1) {
					// Ignore
				}
				String exception_msg = String.format("* %s %s",
						client.nickname, "has been disconnected.");
				broadcast(exception_msg);
			}
		}
	}

	/**
	 * 发生错误时调用
	 * 
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("发生错误");
		error.printStackTrace();
	}

	/**
	 * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
	 * 
	 * @param message
	 * @throws IOException
	 */
	public void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
		// this.session.getAsyncRemote().sendText(message);
	}

	/**
	 * 当前客户端连接的总数
	 * 
	 * @return
	 */
	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	/**
	 * 在线数加1
	 */
	public static synchronized void addOnlineCount() {
		WebSocket.onlineCount++;
	}

	/**
	 * 在线数减1
	 */
	public static synchronized void subOnlineCount() {
		WebSocket.onlineCount--;
	}
}
